const http = require('http')
const url = require('url')
const path = require('path')
const mime = require('mime')
const fs = require('fs')

const server = http.createServer((req, res) => {
  // 路径解析
  let { pathname, query } = url.parse(req.url)
  pathname = decodeURIComponent(pathname)
  let absPath = path.join(__dirname, pathname)

  // 文件 stat
  fs.stat(absPath, (err, statObj) => {
    if(err) {
      res.statusCode = 404
      res.end('Not Found')
      return
    }

    // 路径类型处理
    if(statObj.isFile()) {
      fs.readFile(absPath, (err, data) => {
        res.setHeader('Content-type', mime.getType(absPath) + ';charset=utf-8')
        res.end(data)
      })
    } else {
      fs.readFile(path.join(absPath, 'index.html'), (err, data) => {
        res.setHeader('Content-type', mime.getType(absPath) + ';charset=utf-8')
        res.end(data)
      })
    }
  })

})

server.listen('666', () => {
  console.log(('服务启动了'));
})
